import { Modal, Form, Input, Button, message } from 'antd';
import { request } from '@umijs/max';
import { useState, useEffect } from 'react';
import { useLocation } from '@umijs/max';

const { Item } = Form;
type Props = {
  type: 'edit' | 'add';
  visible: boolean;
  defaultCategory?: any;
  onClose: () => void;
  reload?: () => void;
};

const Dialog: React.FC<Props> = (props) => {
  const { type, visible, onClose, defaultCategory = {} } = props;
  const [categoryLevel, setCategoryLevel] = useState(1);
  const [parentId, setParentId] = useState(0);
  const [form] = Form.useForm();
  const location = useLocation();

  useEffect(() => {
    const query = new URLSearchParams(location.search);
    // 通过 get 方法获取具体的查询参数值
    const level = Number(query.get('level')) || 1;
    const parent_id = Number(query.get('parent_id')) || 0;
    setCategoryLevel(level);
    setParentId(parent_id);
  }, [location.search]);

  const handleSubmit = () => {
    form.validateFields().then(() => {
      if (type === 'add') {
        // 添加分类
        request('/categories', {
          method: 'post',
          data: {
            categoryLevel,
            parentId,
            categoryName: form.getFieldValue('categoryName'),
            categoryRank: form.getFieldValue('categoryRank'),
          },
          headers: {
            token: localStorage.getItem('token') || '',
          },
        }).then(() => {
          message.success('添加成功');
          onClose();
        });
      } else {
        // 修改分类
        request('/categories', {
          method: 'put',
          data: {
            ...defaultCategory,
            categoryName: form.getFieldValue('categoryName'),
            categoryRank: form.getFieldValue('categoryRank'),
          },
          headers: {
            token: localStorage.getItem('token') || '',
          },
        }).then(() => {
          message.success('修改成功');
          onClose();
        });
      }
    });
  };

  return (
    <>
      <Modal
        title={type === 'add' ? '添加分类' : '修改分类'}
        open={visible}
        destroyOnClose
        width={400}
        onCancel={onClose}
        footer={
          <div>
            <Button onClick={onClose}>取 消</Button>
            <Button type="primary" onClick={handleSubmit}>
              确 定
            </Button>
          </div>
        }
      >
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          initialValues={defaultCategory}
          form={form}
        >
          <Item
            label="商品名称"
            name="categoryName"
            rules={[{ required: true, message: '名称不能为空' }]}
          >
            <Input type="text" />
          </Item>
          <Item
            label="排序值"
            name="categoryRank"
            rules={[{ required: true, message: '编号不能为空' }]}
          >
            <Input type="number" />
          </Item>
        </Form>
      </Modal>
    </>
  );
};

export default Dialog;
